
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rfid/http/api.dart';
import 'package:rfid/util/toast_util.dart';

import '../main.dart';
import '../util/timer_manager.dart';
import '../widget/clipper.dart';
import '../widget/device_name_widget.dart';
import '../widget/focus_killer.dart';

class CameraPage extends StatefulWidget {
  const CameraPage({super.key});

  @override
  State<CameraPage> createState() => _CameraPageState();
}

class _CameraPageState extends State<CameraPage> {

  RxInt cameraId = RxInt(-1);
  RxBool preview = RxBool(false);
  Size? _previewSize;
  StreamSubscription<CameraErrorEvent>? _errorStreamSubscription;
  StreamSubscription<CameraClosingEvent>? _cameraClosingStreamSubscription;
  Timer? _timer;
  var countTime = 120;

  @override
  void initState() {
    super.initState();


    _openCamera();

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.normal,(){
        currentTask.clear();
        Get.back();
      });

    });

  }

  _start(){
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      if (countTime <= 0) {
        if(_timer!=null){
          _timer!.cancel();
          _timer = null;
        }
        return;
      }
      countTime = countTime-5;
      _computeTakePicture();

    });
  }

  _openCamera() async {
     await _fetchCameras();
    // _initializeCamera(camera);
  }

  @override
  void dispose() {
    _disposeCurrentCamera();
    _errorStreamSubscription?.cancel();
    _errorStreamSubscription = null;
    _cameraClosingStreamSubscription?.cancel();
    _cameraClosingStreamSubscription = null;
    _timer?.cancel();
    _timer = null;
    super.dispose();
  }

  Future _fetchCameras() async {
    List<CameraDescription> cameras = <CameraDescription>[];

    try {
      cameras = await CameraPlatform.instance.availableCameras();
      if (cameras.isEmpty) {
        toastError('没有可用的摄像头');
      } else {
        _initializeCamera(cameras[0 % cameras.length]);
      }
    } on PlatformException catch (e) {
      toastError('${e.message}');
    }

  }

  Future _initializeCamera(CameraDescription camera) async {
    assert(cameraId.value == -1);
    int cId = -1;
    try {
      cId = await CameraPlatform.instance.createCamera(
        camera,
        ResolutionPreset.veryHigh,
        enableAudio: false,
      );

      unawaited(_errorStreamSubscription?.cancel());
      _errorStreamSubscription = CameraPlatform.instance
          .onCameraError(cId)
          .listen((e){
            if (mounted) {
              _disposeCurrentCamera();
              _fetchCameras();
            }
         });

      unawaited(_cameraClosingStreamSubscription?.cancel());
      _cameraClosingStreamSubscription = CameraPlatform.instance
          .onCameraClosing(cId)
          .listen((e){

          });

      final Future<CameraInitializedEvent> initialized =
          CameraPlatform.instance.onCameraInitialized(cId).first;

      await CameraPlatform.instance.initializeCamera(
        cId,
      );
      final CameraInitializedEvent event = await initialized;
      _previewSize = Size(
        event.previewWidth,
        event.previewHeight,
      );
      cameraId.value = cId;
      _start();
    } on CameraException catch (_) {
      try {
        if (cId >= 0) {
          await CameraPlatform.instance.dispose(cId);
        }
      } on CameraException catch (e) {
        toastError('${e.description}');
      }
      cameraId.value = -1;
    }
  }

  Future _disposeCurrentCamera() async {
    if (cameraId.value >= 0) {
      try {
        await CameraPlatform.instance.dispose(cameraId.value);
        cameraId.value = -1;
      } on CameraException catch (e) {
        toastError('${e.description}');
      }
    }
  }
  _computeTakePicture() async {
      XFile file = await CameraPlatform.instance.takePicture(cameraId.value);
      // var data = await compute(_takePicture, (file,currentTask));
      // var data = _takePicture(file,currentTask);
      var bytes = await file.readAsBytes();
      String base64 = base64Encode(bytes);
      String base64Image = "data:image/png;base64,$base64";
      var data = await faceAdd(currentTask.uid,currentTask.uName,base64Image);
      File f = File.fromUri(Uri.file(file.path));
      f.delete();
      if(data.$1){
        toastWarn('认证成功');
        tts.speak("认证成功");
        _timer?.cancel();
        _timer = null;
        preview.value = true;
        await CameraPlatform.instance.pausePreview(cameraId.value);
      }else{
        toastWarn('${data.$2}');
      }
  }


  static Future _takePicture(message)  async {
    var bytes = await (message.$1).readAsBytes();
    String base64 = base64Encode(bytes);
    String base64Image = "data:image/png;base64,$base64";
    var data = await faceAdd(message.$2.uid,message.$2.uName,base64Image);
    File f = File.fromUri(Uri.file(message.$1.path));
    f.delete();
    return data;
  }

  _appBar(){
    return Container(
      width: double.infinity,
      height: 42.h,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 20,right: 20).w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          deviceNameWidget(),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              focusKiller(),
              Text("",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
            ],
          )
        ],
      ),
    );
  }



  _title(){
    return Container(
        margin: EdgeInsets.only(top: 20.h,left: 20.w,right: 20.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
              onTap: (){
                timer.cancel();
                currentTask.clear();
                Get.back();
              },
              child: Image.asset("assets/images/back.png",width:60.w,height:23.h, fit: BoxFit.fill,),
            ),

            Obx(() => Text("${timer.normalTime.value}s",style: TextStyle(color: Colors.white,fontSize: 12.sp),))
          ],
        )
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: <Widget>[
            _appBar(),
            _title(),
            SizedBox(height: 40.h),
            Obx(() => cameraId.value > 0?
              Align(
                child: ClipOval(
                  // clipper: ClipperOvalPath(),
                  child: AspectRatio(
                      aspectRatio: _previewSize!.width / _previewSize!.height,
                      child: CameraPlatform.instance.buildPreview(cameraId.value)
                  ),
                )
              ):
              Align(
                child: SizedBox(
                    width: 150.w,
                    height: 150.w,
                    child: const ClipOval(
                      child: SizedBox(),
                    )
                ),
              ),
            ),
            SizedBox(height: 30.h),
            Obx(() => preview.value?
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  InkWell(
                    child: Image.asset("assets/images/result_confirm.jpg",height: 36.h, width: 80.w, fit: BoxFit.fill,),
                    onTap: (){
                      timer.cancel();
                      currentTask.clear();
                      Get.back();
                    },
                  ),
                  SizedBox(height: 5.h),
                  InkWell(
                    child:  Text('照片不满意？重拍',style: TextStyle(fontSize: 10.sp, decoration: TextDecoration.underline, color:const Color.fromRGBO(255, 26, 26, 1)),),
                    onTap: () async {
                      preview.value = false;
                      await CameraPlatform.instance.resumePreview(cameraId.value);
                      _start();
                    },
                  )

                ],
              ):
              Text('请把人脸放在指定区域',style: TextStyle(color: Colors.white,fontSize: 10.sp),)
            )

          ],
        ),
      ),
    );
  }
}